#include "device_state_manager.h"
#include "smart_home_ui.h"
#include "ac_control.h"
#include "music_player.h"
#include "light_control.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>

// 静态全局变量
static device_state_t current_state = {0};
static bool manager_initialized = false;

/**
 * @brief 初始化设备状态管理器
 */
void device_state_manager_init(void) {
    if (manager_initialized) {
        return;
    }
    
    // 初始化状态结构体
    memset(&current_state, 0, sizeof(device_state_t));
    current_state.state_restored = false;
    
    // 确保/tmp目录存在
    struct stat st = {0};
    if (stat("/tmp", &st) == -1) {
        printf("警告：/tmp目录不存在\n");
    }
    
    manager_initialized = true;
    // 设备状态管理器初始化完成
}

/**
 * @brief 从各个模块收集当前设备状态
 */
static void collect_current_states(void) {
    // 收集空调状态
    current_state.ac_power = get_ac_power_state();
    current_state.ac_temperature = get_ac_current_temp();
    current_state.ac_mode = get_ac_current_mode();
    current_state.ac_fan_speed = get_ac_current_fan_speed();
    
    // 收集音乐播放器状态
    current_state.music_playing = (music_get_state() == MUSIC_STATE_PLAYING);
    current_state.music_volume = music_get_volume();
    current_state.current_song_index = music_get_current_song_index();
    
    // 收集灯光状态
    current_state.light1_state = global_light1_state;
    current_state.light2_state = global_light2_state;
    current_state.light3_state = global_light3_state;
    current_state.light4_state = global_light4_state;
    
    // 收集窗帘状态
    current_state.curtain_position = global_curtain_position;
    current_state.curtain_auto = global_curtain_auto;
    
    // 保留当前呼叫触发器状态（不进行初始化）
    // 状态由update_xxx_call_triggered函数单独更新
}

/**
 * @brief 保存所有设备状态到文件
 */
bool save_device_states(void) {
    if (!manager_initialized) {
        printf("错误：设备状态管理器未初始化\n");
        return false;
    }
    
    // 收集当前状态
    collect_current_states();
    
    FILE *file = fopen(STATE_FILE_PATH, "w");
    if (!file) {
        printf("错误：无法创建状态文件 %s\n", STATE_FILE_PATH);
        return false;
    }
    
    // 写入文件头注释
    fprintf(file, "# 智能家居设备状态配置文件\n");
    fprintf(file, "# 此文件在关机时自动生成，开机时自动读取\n");
    fprintf(file, "# 请勿手动修改\n\n");
    
    // 保存空调状态
    fprintf(file, "[空调]\n");
    fprintf(file, "ac_power=%d\n", current_state.ac_power ? 1 : 0);
    fprintf(file, "ac_temperature=%d\n", current_state.ac_temperature);
    fprintf(file, "ac_mode=%d\n", current_state.ac_mode);
    fprintf(file, "ac_fan_speed=%d\n", current_state.ac_fan_speed);
    fprintf(file, "\n");
    
    // 保存音乐播放器状态
    fprintf(file, "[音乐播放器]\n");
    fprintf(file, "music_playing=%d\n", current_state.music_playing ? 1 : 0);
    fprintf(file, "music_volume=%d\n", current_state.music_volume);
    fprintf(file, "current_song_index=%d\n", current_state.current_song_index);
    fprintf(file, "\n");
    
    // 保存灯光状态
    fprintf(file, "[灯光控制]\n");
    fprintf(file, "light1_state=%d\n", current_state.light1_state ? 1 : 0);
    fprintf(file, "light2_state=%d\n", current_state.light2_state ? 1 : 0);
    fprintf(file, "light3_state=%d\n", current_state.light3_state ? 1 : 0);
    fprintf(file, "light4_state=%d\n", current_state.light4_state ? 1 : 0);
    fprintf(file, "\n");
    
    // 保存窗帘状态
    fprintf(file, "[窗帘控制]\n");
    fprintf(file, "curtain_position=%d\n", current_state.curtain_position);
    fprintf(file, "curtain_auto=%d\n", current_state.curtain_auto ? 1 : 0);
    fprintf(file, "\n");
    
    // 保存呼叫触发器状态
    fprintf(file, "[呼叫触发器]\n");
    fprintf(file, "dad_call_triggered=%d\n", current_state.dad_call_triggered ? 1 : 0);
    fprintf(file, "mom_call_triggered=%d\n", current_state.mom_call_triggered ? 1 : 0);
    fprintf(file, "son_call_triggered=%d\n", current_state.son_call_triggered ? 1 : 0);
    fprintf(file, "daughter_call_triggered=%d\n", current_state.daughter_call_triggered ? 1 : 0);
    fprintf(file, "\n");
    
    // 保存恢复标记
    fprintf(file, "[系统状态]\n");
    fprintf(file, "state_restored=0\n");  // 重置恢复标记
    
    fclose(file);
    
    // 设备状态已保存到文件
    print_device_states();
    return true;
}

/**
 * @brief 从文件恢复所有设备状态
 */
bool restore_device_states(void) {
    if (!manager_initialized) {
        printf("错误：设备状态管理器未初始化\n");
        return false;
    }
    
    // 检查是否已经恢复过
    if (current_state.state_restored) {
        printf("状态已经恢复过，跳过重复恢复\n");
        return true;
    }
    
    FILE *file = fopen(STATE_FILE_PATH, "r");
    if (!file) {
        printf("状态文件 %s 不存在，使用默认设置\n", STATE_FILE_PATH);
        current_state.state_restored = true;
        return false;
    }
    
    char line[256];
    int value;
    
    // 开始恢复设备状态
    
    while (fgets(line, sizeof(line), file)) {
        // 跳过注释和空行
        if (line[0] == '#' || line[0] == '\n' || line[0] == '[') {
            continue;
        }
        
        // 解析空调状态
        if (sscanf(line, "ac_power=%d", &value) == 1) {
            current_state.ac_power = (value == 1);
            // 注意：不在这里同步空调电源状态，因为用户设置中的ac_power优先级更高
            // 空调电源状态由smart_home_ui.c中的load_user_settings()函数负责恢复
            printf("设备状态文件中的空调电源状态: %s (不应用，以用户设置为准)\n", 
                   current_state.ac_power ? "开启" : "关闭");
        }
        else if (sscanf(line, "ac_temperature=%d", &value) == 1) {
            current_state.ac_temperature = value;
            // 恢复空调温度
            restore_ac_temperature(value);
        }
        else if (sscanf(line, "ac_mode=%d", &value) == 1) {
            current_state.ac_mode = value;
            // 恢复空调模式
            restore_ac_mode(value);
        }
        else if (sscanf(line, "ac_fan_speed=%d", &value) == 1) {
            current_state.ac_fan_speed = value;
            // 恢复空调风速
            restore_ac_fan_speed(value);
        }
        
        // 解析音乐播放器状态
        else if (sscanf(line, "music_playing=%d", &value) == 1) {
            current_state.music_playing = (value == 1);
            // 恢复播放状态
            if (current_state.music_playing) {
                music_play();
            } else {
                music_pause();
            }
        }
        else if (sscanf(line, "music_volume=%d", &value) == 1) {
            current_state.music_volume = value;
            // 恢复音量
            music_set_volume(value);
        }
        else if (sscanf(line, "current_song_index=%d", &value) == 1) {
            current_state.current_song_index = value;
            // 恢复当前歌曲索引
            music_set_current_song_index(value);
        }
        
        // 解析灯光状态
        else if (sscanf(line, "light1_state=%d", &value) == 1) {
            current_state.light1_state = (value == 1);
            global_light1_state = current_state.light1_state;
        }
        else if (sscanf(line, "light2_state=%d", &value) == 1) {
            current_state.light2_state = (value == 1);
            global_light2_state = current_state.light2_state;
        }
        else if (sscanf(line, "light3_state=%d", &value) == 1) {
            current_state.light3_state = (value == 1);
            set_light_state(2, current_state.light3_state);
        }
        else if (sscanf(line, "light4_state=%d", &value) == 1) {
            current_state.light4_state = (value == 1);
            set_light_state(3, current_state.light4_state);
        }
        
        // 解析窗帘状态
        else if (sscanf(line, "curtain_position=%d", &value) == 1) {
            current_state.curtain_position = value;
            global_curtain_position = value;
        }
        else if (sscanf(line, "curtain_auto=%d", &value) == 1) {
            current_state.curtain_auto = (value == 1);
            global_curtain_auto = current_state.curtain_auto;
        }
        
        // 解析呼叫触发器状态
        else if (sscanf(line, "dad_call_triggered=%d", &value) == 1) {
            current_state.dad_call_triggered = (value == 1);
        }
        else if (sscanf(line, "mom_call_triggered=%d", &value) == 1) {
            current_state.mom_call_triggered = (value == 1);
        }
        else if (sscanf(line, "son_call_triggered=%d", &value) == 1) {
            current_state.son_call_triggered = (value == 1);
        }
        else if (sscanf(line, "daughter_call_triggered=%d", &value) == 1) {
            current_state.daughter_call_triggered = (value == 1);
        }
    }
    
    fclose(file);
    
    // 标记已恢复
    current_state.state_restored = true;
    
    // 设备状态恢复完成
    print_device_states();
    return true;
}

/**
 * @brief 检查是否已经恢复过状态
 */
bool is_state_restored(void) {
    return current_state.state_restored;
}

/**
 * @brief 清除状态文件
 */
void clear_saved_states(void) {
    if (unlink(STATE_FILE_PATH) == 0) {
        printf("状态文件已清除\n");
    } else {
        printf("清除状态文件失败或文件不存在\n");
    }
    current_state.state_restored = false;
}

/**
 * @brief 获取当前设备状态
 */
device_state_t get_current_device_states(void) {
    collect_current_states();
    return current_state;
}

/**
 * @brief 打印当前设备状态（调试用）
 */
void print_device_states(void) {
    printf("=== 当前设备状态 ===\n");
    printf("空调：%s，温度：%d°C，模式：%d，风速：%d\n", 
           current_state.ac_power ? "开启" : "关闭",
           current_state.ac_temperature,
           current_state.ac_mode,
           current_state.ac_fan_speed);
    printf("音乐：%s，音量：%d%%，歌曲索引：%d\n",
           current_state.music_playing ? "播放中" : "暂停",
           current_state.music_volume,
           current_state.current_song_index);
    printf("灯光：L1=%s，L2=%s，L3=%s，L4=%s\n",
           current_state.light1_state ? "开" : "关",
           current_state.light2_state ? "开" : "关",
           current_state.light3_state ? "开" : "关",
           current_state.light4_state ? "开" : "关");
    printf("窗帘：位置=%d%%，自动=%s\n",
           current_state.curtain_position,
           current_state.curtain_auto ? "开启" : "关闭");
    printf("烟雾监控：浓度=%u，警报=%s，蜂鸣器=%s\n",
           current_state.smoke_concentration,
           current_state.smoke_alarm_active ? "激活" : "正常",
           current_state.buzzer_enabled ? "启用" : "禁用");
    printf("呼叫触发器：爸爸=%s，妈妈=%s，儿子=%s，女儿=%s\n",
           current_state.dad_call_triggered ? "已触发" : "未触发",
           current_state.mom_call_triggered ? "已触发" : "未触发",
           current_state.son_call_triggered ? "已触发" : "未触发",
           current_state.daughter_call_triggered ? "已触发" : "未触发");
    printf("状态恢复标记：%s\n", current_state.state_restored ? "已恢复" : "未恢复");
    printf("==================\n");
}

/**
 * @brief 更新烟雾监控状态
 */
void update_smoke_monitor_state(uint32_t concentration, bool alarm_active, bool buzzer_enabled) {
    current_state.smoke_concentration = concentration;
    current_state.smoke_alarm_active = alarm_active;
    current_state.buzzer_enabled = buzzer_enabled;
}

/**
 * @brief 获取烟雾监控状态
 */
void get_smoke_monitor_state(uint32_t *concentration, bool *alarm_active, bool *buzzer_enabled) {
    if (concentration) {
        *concentration = current_state.smoke_concentration;
    }
    if (alarm_active) {
        *alarm_active = current_state.smoke_alarm_active;
    }
    if (buzzer_enabled) {
        *buzzer_enabled = current_state.buzzer_enabled;
    }
}

/**
 * @brief 更新爸爸呼叫触发器状态
 */
void update_dad_call_triggered(bool triggered) {
    printf("update_dad_call_triggered: 设置爸爸呼叫状态为 %s\n", triggered ? "true" : "false");
    current_state.dad_call_triggered = triggered;
}

/**
 * @brief 更新妈妈呼叫触发器状态
 */
void update_mom_call_triggered(bool triggered) {
    current_state.mom_call_triggered = triggered;
}

/**
 * @brief 更新儿子呼叫触发器状态
 */
void update_son_call_triggered(bool triggered) {
    current_state.son_call_triggered = triggered;
}

/**
 * @brief 更新女儿呼叫触发器状态
 */
void update_daughter_call_triggered(bool triggered) {
    current_state.daughter_call_triggered = triggered;
}
